import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {getUrlParam} from '../data/util'
import {header} from '../data/config'
import store from 'store'

const base           = url.base,
  editBuildConvert   = request.editBuildConvert;

const title= '转换楼盘',
      action = '修改';

let id = getUrlParam('id'),
    storeData   = store.get('storeData');

let form = new Vue({
  el: '#form',
  data: () => { // 设置成函数才可以调用$options.data()方法来清空数据
    return {
      id: '',
      channel: '',
      convertId: '',
      convertName: '',
      isLock: false
    }
  },
  mounted: function () { // 生命周期

    this.$data.convertId = getUrlParam('id')

    $.extend(this.$data, storeData)

    valid()
  }
})

function valid() {

  let form_valid,
    $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前
    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true

      let data = {
        buildingId: getUrlParam('id'),
        convertName: form.$data.convertName,
        convertId: form.$data.convertId,
        channel: form.$data.channel,
        id: form.$data.id
      };

      $.ajax({
        url: base + editBuildConvert,
        type: 'POST',
        headers: header,
        contentType: 'application/json',
        data: JSON.stringify(data)
      })
        .done(function (res) {
          console.log(res)

          if (res.code === -1) {
            layer.msg('修改转换楼盘信息失败', {
              icon: 5
            })

            form.isLock = false

            return
          }

          layer.msg(`${action}${title}成功`, {
            icon: 6
          })

          // 重置表单
          // $.extend(form.$data, form.$options.data())

          setTimeout(() => {
            window.location.href = './convert.html?id=' + id;
          }, 1000)
        })
        .fail(function (res) {
          console.log(res)

          layer.msg(`修改转换楼盘信息失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function (res) {

          layer.close(loading_modal)
          form.isLock = false

        })

    }
  })

  // 验证
  form_valid = $form.validate({
    rules: {
      convertName: {
        required: true
      },
      convertId: {
        required: true
      },
      channel: {
        required: true
      },
    }
  })
}

$('#convert').on('click', (e) => {

  e.preventDefault;

  window.location.href = './convert.html?id=' + id;
})